//
//  LocationListViewController.m
//  auditorias
//
//  Created by Mauro on 7/29/13.
//  Copyright (c) 2013 Antilope. All rights reserved.
//

#import "LocationListViewController.h"
#import "SharedMemory.h"
#import "ControlVariables.h"
#import "PointOfSell.h"
#import "User.h"
#import <math.h>
#import "MBProgressHUD.h"
#import "DataLoader.h"

@interface LocationListViewController ()

@end

@implementation LocationListViewController

@synthesize items;
@synthesize table;
@synthesize currentSelection;


//#define MAX_TO_DISPLAY 10

- (void) dealloc
{
    [items release], items = nil ;
    [table release], table = nil;
    [_topBarView release];
    [super dealloc];
}

- (void)viewDidUnload
{
    self.items = nil;
    self.table = nil;
    [super viewDidUnload];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    [TopBarViewController setTitleLabelOf:_topBarView text:kTopBarTitleLocationList];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    SharedMemory *mem = [SharedMemory sharedInstance];
    self.currentSelection = mem.pointOfSellIndex;
    self.items = [[[NSMutableArray alloc] init] autorelease];
    [self loadTable];
    
}

- (void)dataReadyWithLoader:(DataLoader*) dataLoader;
{
    @try {
        [dataLoader release];
    }
    @catch (NSException * e) { }
    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    [self loadTable];
}

- (void)dataNotReadyWithLoader:(DataLoader*) dataLoader;
{
    @try {
        [dataLoader release];
    }
    @catch (NSException * e) { }
    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    [SharedMemory showError:kErrorMessageNotRespondingTitle andText:kErrorMessageNotResponding];
    [self loadTable];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)numberOfSectionsInTableView: (UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView: (UITableView *)tableView numberOfRowsInSection: (NSInteger)section
{
    return [items count];
}

- (UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
    //SharedMemory *mem = [SharedMemory sharedInstance];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LocationMenuCell"];
    PointOfSell* pdv = [self.items objectAtIndex:[indexPath row] ];
    
    UILabel *descriptionLabel = (UILabel *)[cell viewWithTag:11];
    [descriptionLabel setText:pdv.description];
    UIView *selectionColor = [[[UIView alloc] init] autorelease];
    UIView *bgColor = [[[UIView alloc] init] autorelease];
    
    selectionColor.backgroundColor = bgColor.backgroundColor = [self isOnItemsDoneList:pdv] ? [UIColor colorWithRed:(221/255.0) green:(221/255.0) blue:(221/255.0) alpha:1] : [UIColor clearColor];
    
    cell.backgroundView = bgColor;
    cell.selectedBackgroundView = selectionColor;
    
    return cell;
}

//If its marked, then it returns true.
- (bool) isOnItemsDoneList:(PointOfSell*) pdv
{
    SharedMemory *mem = [SharedMemory sharedInstance];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary* dic = [defaults dictionaryForKey:ONEMONTH_PDVS_KEY];
    NSString* key = [mem makePDVnId:pdv];
    NSString* dateString = (dic==nil)? nil : [dic objectForKey:key];
    if (dateString!=nil) {
        if(![mem isOlderThanAMonth:dateString]){
            //If it wasn't rejected, then the onemonthPDVsPreferences rule the color.
            if (pdv.statusType != PDV_TYPE_REJECTED)
                return true;
            
            //Special case: when the onemonthPDVsPreferences tells the Audit was audited recently (less than a month) but
            //the fetched PDV tells it was rejected, then, the most recent information should rule the color of the item.
            double dateLastSync =  ([defaults objectForKey:SHARED_PREFS_LAST_SYNC] == nil) ? 0 : [[defaults objectForKey:SHARED_PREFS_LAST_SYNC] doubleValue];
            double dateLastFetch = ([defaults objectForKey:SHARED_PREFS_LAST_FETCH] == nil) ? 0 : [[defaults objectForKey:SHARED_PREFS_LAST_FETCH] doubleValue];
            double date = [dateString doubleValue] ;
            return (date > dateLastFetch || date > dateLastSync);
        }
        [mem forgetKeyOn:ONEMONTH_PDVS_KEY key:key];
    }
    if (pdv.statusType == PDV_TYPE_APPROVED || pdv.statusType == PDV_TYPE_PENDING)
        return true;
    else if (pdv.statusType == PDV_TYPE_REJECTED)
        return false;
    return false;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //[tableView deselectRowAtIndexPath:indexPath animated:NO];
    //UITableViewCell *oldCell = [tableView dequeueReusableCellWithIdentifier:@"LocationMenuCell"];
    self.currentSelection = [indexPath row];
    SharedMemory *mem = [SharedMemory sharedInstance];
    mem.pointOfSellIndex = self.currentSelection;
}


- (IBAction)refreshButtonTapped:(id)sender
{
    [MBProgressHUD hideHUDForView:self.view animated:NO];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = kLoadingMessage;
    DataLoader *loader = [[DataLoader alloc] initWithCaller:self successSel:@selector(dataReadyWithLoader:) failureSel:@selector(dataNotReadyWithLoader:)];
    [loader loadPointsOfSell:[LocationListenerViewController getLastGoodLocation]];
}

- (IBAction)finishButtonTapped:(id)sender
{
    SharedMemory *mem = [SharedMemory sharedInstance];
    if(mem.pointOfSellIndex==-1 || [items count]<=mem.pointOfSellIndex){
        [SharedMemory showError:@"" andText:location_must_select];
        return;
    }
    [self.tabBarController setSelectedIndex:1];
}

- (IBAction)mapButtonTapped:(id)sender
{
    [self performSegueWithIdentifier:@"ToMap" sender:self];
}

- (void) loadTable
{
    [self makeItemList];
    [self.table reloadData];
    //To start with a marked one
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.currentSelection inSection:0];
    [self.table selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
    [self.table.delegate tableView:self.table didSelectRowAtIndexPath:indexPath];
}

-(void) makeItemList
{
    SharedMemory *mem = [SharedMemory sharedInstance];
    int itemsCount = [mem.pointsOfSell count];
    
    CLLocation *loc =[LocationListenerViewController getLastGoodLocation];
    if (loc!=nil) {
        CLLocationCoordinate2D userLoc = [loc coordinate];
        CLLocation* userLocFull = [[[CLLocation alloc] initWithLatitude:userLoc.latitude longitude:userLoc.longitude] autorelease];
        NSArray *sortedArray = [mem.pointsOfSell sortedArrayUsingComparator:^NSComparisonResult(id chair1, id chair2) {
            CLLocation* c1 = [[[CLLocation alloc] initWithLatitude:((PointOfSell*)chair1).geoLocation.latitude longitude:((PointOfSell*)chair1).geoLocation.longitude] autorelease];
            CLLocation* c2 = [[[CLLocation alloc] initWithLatitude:((PointOfSell*)chair2).geoLocation.latitude longitude:((PointOfSell*)chair2).geoLocation.longitude] autorelease];
            double dist1 = [c1 distanceFromLocation:userLocFull];
            double dist2 = [c2 distanceFromLocation:userLocFull];
            return ((dist1-dist2) == 0)? NSOrderedSame : ((dist1<dist2) ? NSOrderedAscending: NSOrderedDescending );
        }];
        [mem.pointsOfSell removeAllObjects];
        [mem.pointsOfSell addObjectsFromArray:sortedArray];
    }
    [self.items removeAllObjects];
    for (int i = 0; i < itemsCount; i++) {
        [self.items addObject:[mem.pointsOfSell objectAtIndex:i]];
    }
}


@end
